package com.hooper.dp.aop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hooper.dp.dto.UserDTO;
import com.hooper.dp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hooper.dp.constant.UserConstant.*;

/**
 * 刷新token 拦截器
 *
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/02/25/15:43
 */
@Slf4j
public class TokenRefreshInterceptor implements HandlerInterceptor {
    public TokenRefreshInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到请求：{}", request.getRequestURI());
        //从请求头中获取token信息
        String token = request.getHeader("authorization");
        //若请求头不含token，直接放行，交给Login拦截器进行处理
        if (StringUtils.isBlank(token)) {
            return true;
        }
        //从redis中获取用户，若用户为空，则表示未登录
        String key = USER_INFO_CACHE + token;
        Map<Object, Object> userInfo = stringRedisTemplate.opsForHash().entries(key);
        if (CollectionUtil.isEmpty(userInfo)) {
            //防止空指针
            return true;
        }
        //转为对象，并存入ThreadLocal中
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userInfo, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        //token续费
        stringRedisTemplate.expire(key, TOKEN_TTL, TimeUnit.MINUTES);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
